package com.example.douyinproject;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.widget.RadioGroup;

import com.example.douyinproject.firstpage_news.FirstPageFragment;
import com.example.douyinproject.local_music.LocalFragment;
import com.example.douyinproject.me.MeFragment;
import com.example.douyinproject.video.VideoFragment;

import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.jzvd.JzvdStd;

public class MainActivity extends AppCompatActivity {
    RadioGroup mainRg;
    List<Fragment>fragmentList;
    private FragmentManager fm; //碎片管理者

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        x.Ext.init(getApplication()); //声明xutils
        initFrag();
        mainRg = findViewById(R.id.main_rg);
        mainRg.setOnCheckedChangeListener(listener);
    }

    /*初始化fragment的方法*/
    private void initFrag() {
        //将要显示的fragment放到一个集合里便于管理
        fragmentList = new ArrayList<>();
        fragmentList.add(new FirstPageFragment());
        fragmentList.add(new VideoFragment());
        fragmentList.add(new LocalFragment());
        fragmentList.add(new MeFragment());

        //将4个fragment添加到activity当中
        fm = getSupportFragmentManager();
        FragmentTransaction tran = fm.beginTransaction(); //事务对象
        //将4个fragment都添加到指定的布局，同时隐藏起来，只显示第一个
        for (int i = 0; i < fragmentList.size(); i++) {
            tran.add(R.id.main_layout,fragmentList.get(i));
            tran.hide(fragmentList.get(i));
        }
        tran.show(fragmentList.get(0));
        tran.commit(); //提交事务
    }

    RadioGroup.OnCheckedChangeListener listener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.main_rb1:
                    changeFrag(0);
                    JzvdStd.releaseAllVideos();
                    break;
                case R.id.main_rb2:
                    changeFrag(1);
                    break;
                case R.id.main_rb3:
                    changeFrag(2);
                    JzvdStd.releaseAllVideos();
                    break;
                case R.id.main_rb4:
                    changeFrag(3);
                    JzvdStd.releaseAllVideos();
                    break;
            }
        }
    };

    /*切换fragment的方法*/
    private void changeFrag(int i) {
        FragmentTransaction tr = fm.beginTransaction();
        for (int j = 0; j < fragmentList.size(); j++) {
            tr.hide(fragmentList.get(j));
        }
        tr.show(fragmentList.get(i));
        tr.commit();
    }
}